package com.mz361.stdapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.mz361.common.utils.*;
import com.mz361.modules.system.service.OrderService;
import com.mz361.stdapi.domain.StandardTable;
import com.mz361.stdapi.service.StandardTableService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateResponse;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
public class MultithreadScheduleTask {
    @Autowired
    UploadBailianUtil uploadBailianUtil;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    OrderService orderService;
    @Autowired
    StandardTableService standardTableService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    private static final String sycnStandardsUrl = "/api/v1/sycnStandards";


    /**
     * 价格更新
     */
    @Async
    @Scheduled(cron = "0 5 1 * * ?")
    public void delPayOrder() {
        System.out.println("----开始处理过期支付订单-----");
        orderService.delNopayList();

    }

    /**
     * 同步新增题录数据及pdf文件
     */
    @Async
    @Scheduled(cron = "0 0 1 * * ?")
    public void sycData() {
        System.out.println("----开始同步标准PDF-----");
        HashMap<String, String> param = new HashMap<>();
        ElasticsearchRestTemplate restTemplate = new ElasticsearchRestTemplate(restHighLevelClient);
        for (int i = -1; i > -2; i--) {
            Date dayDate = DateUtils.getDayAfter(new Date(), i);
            System.out.println("请求日期：" + DateUtils.format(dayDate));
            param.put("day", DateUtils.format(dayDate, "yyyy-MM-dd"));
            String results = HttpServletUtil.sendGetRequestNeedParams("https://epsciapi.spc.net.cn" + sycnStandardsUrl, param, null);
            JSONObject jsonObject = JSONObject.parseObject(results);
            if (jsonObject.getInteger("code") == 200) {
                Map<String, JSONObject> dataMap = JSONObject.parseObject(jsonObject.getJSONObject("data").toJSONString(), HashMap.class);
                if (dataMap != null) {
                    for (String key : dataMap.keySet()) {
                        JSONObject jsonObj = dataMap.get(key);
                        Long id = jsonObj.getLong("id");

                        StandardTable standardTable = restTemplate.get(String.valueOf(id), StandardTable.class);
                        if (standardTable != null) {//已存在，则更新数据
                            Document doc = Document.create();
                            boolean flag = false;
                            //判断状态是否有改变
                            if (!StringUtil.equals(standardTable.getFn_StandStatus(), jsonObj.getString("fn_StandStatus"))) {
                                doc.put("fn_StandStatus", jsonObj.getString("fn_StandStatus"));
                                doc.put("fn_A461", jsonObj.getString("fn_A461"));
                                doc.put("fn_A462", jsonObj.getString("fn_A462"));
                                doc.put("fn_StandClass", jsonObj.getString("fn_StandClass"));
                                doc.put("fn_StandType", jsonObj.getString("fn_StandType"));
                                flag = true;

                            }
                            if (StringUtil.notEmpty(jsonObj.getString("fn_filePath"))) {
                                doc.put("fn_HavePDF", "1");
                                flag = true;
                            }
                            if (flag) {
                                UpdateQuery updateQuery = UpdateQuery.builder(String.valueOf(id))
                                        .withDocument(doc)
                                        .build();
                                IndexCoordinates indexCoordinate = IndexCoordinates.of("standard_info");
                                UpdateResponse updateResponse = restTemplate.update(updateQuery, indexCoordinate);
                                System.out.println("exit:" + id + "-------" + updateResponse.getResult());
                            }
                        } else {//新数据保存
                            standardTable = jsonObj.toJavaObject(StandardTable.class);
                            restTemplate.save(standardTable);
                            System.out.println("save:" + id);
                        }

                        if (!redisUtil.hexists("STANDARD:FILEPATH", key) && StringUtil.notEmpty(jsonObj.getString("fn_filePath"))) {
                            redisUtil.hSet("STANDARD:FILEPATH", key, jsonObj.getString("fn_filePath"));
                        }
                    }
                }

            }
        }

    }

    //    @Scheduled(fixedDelay = 10 * 24 * 60 * 60 * 1000)//10天
    public void uploadBailian() {
        log.info("----开始上传百炼PDF-----");
        int pageSize = 50;
        boolean flag = true;
        int pageIndex = 1;
        int sumPage = 2;
        String standClass = "DFBZ";
        String categoryId = "cate_2ec8b0d140374d5cafe5874c0fe4cabd_10253128";
        log.info("standClass:{} categoryId:{}", standClass, categoryId);
        while (true) {
            System.out.println(pageIndex + "页开始执行");
            if (pageIndex > sumPage) {
                break;
            }
            Page<StandardTable> standardTablePage = standardTableService.getAllByStandClass(standClass, pageIndex, pageSize);
            sumPage = standardTablePage.getTotalPages();
            List<StandardTable> standardTableList = standardTablePage.getContent();
            standardTableList.forEach(standardTable -> {
                        String standardNo = standardTable.getFn_A100();
                        if (StringUtil.notEmpty(standardNo)) {
                            String pdfName = redisUtil.hGet("STANDARD:FILEPATH", StringUtil.md5(standardNo));
                            if (StringUtil.notEmpty(pdfName)) {
                                pdfName = "/home/pdffiles/" + pdfName;
                                UploadBailian uploadBailian = new UploadBailian(uploadBailianUtil, pdfName, categoryId);
                                uploadBailian.run();
                            }
                        }
                    }
            );
            log.info(pageIndex + "页结束执行");
            pageIndex++;

        }

    }

    //    @Scheduled(fixedDelay = 10 * 24 * 60 * 60 * 1000)//10天
    public void uploadXmlBailian() {
        log.info("----开始上传百炼XML-----");

        String categoryId = "cate_2ec8b0d140374d5cafe5874c0fe4cabd_10253128";
        log.info("categoryId:{}", categoryId);
        String rootDirPath = "/home/xmlfiles";
        File rootDir = new File(rootDirPath);
        if (rootDir.exists() && rootDir.isDirectory()) {
            // 开始遍历目录及子目录下的xml文件
            processDirectory(rootDir);
        } else {
            System.out.println("指定的根目录不存在或不是一个目录！");
        }
    }

    public void processDirectory(File dir) {
        File[] files = dir.listFiles();
        String categoryId = "cate_dc5efcfdd4954c6fad1e852497183a1d_10253128";
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 如果是子目录，则递归调用processDirectory继续遍历该子目录
                    processDirectory(file);
                } else if (file.isFile() && file.getName().toLowerCase().endsWith(".xml")) {
                    // 如果是文件且扩展名是.xml，则修改扩展名
                    String newFileName = changeExtension(file.getName(), ".txt");
                    File newFile = new File(file.getParent(), newFileName);
                    if (file.renameTo(newFile)) {

                        System.out.println("已将文件 " + file.getName() + " 重命名为 " + newFileName);
                        if (newFileName.indexOf("-gb") > 0) {
                            categoryId = "cate_bf3b45905b0e4967bc22631d7cfa0682_10253128";
                        }
                        if (newFileName.indexOf("-jjf") > 0) {
                            categoryId = "cate_d5d42f0af04c48bfa023f49966d45f61_10253128";
                        }
                        if (newFileName.indexOf("-db") > 0) {
                            categoryId = "cate_685f054df5e04cb69fc7b4e2474f223a_10253128";
                        }

                        UploadBailian uploadBailian = new UploadBailian(uploadBailianUtil, "/home/xmlfiles/" + newFileName, categoryId);
                        uploadBailian.run();
                    } else {
                        System.out.println("重命名文件 " + file.getName() + " 失败！");
                    }
                }
            }
        }
    }

    public static String changeExtension(String fileName, String newExtension) {
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex > 0) {
            return fileName.substring(0, lastIndex) + newExtension;
        }
        return fileName + newExtension;
    }

}

class UploadBailian implements Runnable {

    UploadBailianUtil uploadBailianUtil;
    String pdfName;
    String categoryId;

    UploadBailian(UploadBailianUtil uploadBailianUtil, String pdfName, String categoryId) {
        this.uploadBailianUtil = uploadBailianUtil;
        this.pdfName = pdfName;
        this.categoryId = categoryId;
    }

    @SneakyThrows
    @Override
    public void run() {
        try {
            uploadBailianUtil.uploadBailian(pdfName, categoryId);
        } catch (Exception e) {
            System.out.println("pdfName = " + pdfName + " error:" + e.getMessage());

        }

    }
}
